package zcw.com.lib_leet_code;

import zcw.com.lib_leet_code.bean.ListNode;
import zcw.com.lib_leet_code.util.Util;

/**
 * Created by 朱城委 on 2021-8-25.<br><br>
 *
 * 中等：反转链表 II
 */
public class Topic92 {

    public static void main(String[] args) {
        Topic92 instance = new Topic92();

        int[] array = new int[] {1,2,3,4,5};
        ListNode head = Util.createList(array);
        Util.printList(instance.reverseBetween(head, 2, 4));

        array = new int[] {5};
        head = Util.createList(array);
        Util.printList(instance.reverseBetween(head, 1, 1));
    }

    public ListNode reverseBetween(ListNode head, int left, int right) {
        if(head == null || head.next == null || left == right) {
            return head;
        }

        ListNode start = new ListNode(0);
        start.next = head;
        ListNode pre = start;

        for(int i = 1; i < left; i++) {
            pre = pre.next;
        }

        pre.next = helper(pre.next, right - left);
        return start.next;
    }

    private ListNode helper(ListNode head, int len) {
        ListNode curr = head;
        ListNode newHead = null;

        for(int i = 0; i <= len; i++) {
            ListNode temp = curr.next;
            curr.next = newHead;
            newHead = curr;
            curr = temp;
        }

        head.next = curr;
        return newHead;
    }
} 
